//
//  SEGTopicDetailViewModel.m
//  Commom
//
//  Created by 梁学彰 on 2020/6/6.
//

#import "SEGTopicDetailViewModel.h"

@implementation SEGTopicDetailViewModel
#pragma mark - life cycle
- (instancetype)init {
    if (self = [super init]) {
        [self initData];
    }
    return self;
}

#pragma mark - init
- (void)initData {
    self.tencentAdRenderCount = 10;
    self.imageType = NO;
}

#pragma mark - send request
- (RACSignal *)requestTopicDetails{
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        [self.topicManager requestTopicDetailWithId:self.objId finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
            if (!isSuccessed) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }
            SEGSharedTopicDetailInfoModel *model = self.topicManager.topicDetailModel.model;
            self.topicModel = model;
            self.imageType = self.topicModel.pgcType.integerValue == 2; //1为文字话题 2为图文话题
            if (!self.imageType) {//文字话题需要请求是否展示评论弹窗广告
                [subscriber sendNext:nil];
                
            }
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)loadDataWithFresh:(BOOL)fresh {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        if (fresh) {
            self.pageNum = 1;
        }else {
            self.pageNum ++;
        }
        
        [self.topicManager requestTopicCommentListByObjId:self.topicModel.objId objType:self.topicModel.objType pgcType:self.topicModel.pgcType.integerValue  pageNo:self.pageNum pageSize:20 Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
            self.bottomLoading = NO;
            if (!isSuccessed) {
                if (self.pageNum != 1) {
                    self.pageNum -- ;
                }
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }
            self.dataList = self.topicManager.topicCommentList.mutableCopy;
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
    return signal;
}



#pragma mark - custom delegate

#pragma mark - system delegate

#pragma mark - event response
- (RACSignal *)didClickLikeWithModel:(SEGFindQuizListByQuizTypeModel *)model {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        
        SEGProfileModel* sysAccount = [SEGProfileManager sharedManager].profile;
        NSString* communityName = [NSString stringWithFormat:@"来自%@ %@", sysAccount.city, sysAccount.communityName];
        
        if ([[model.isParise stringValue]isEqualToString:@"1"]) {
            //这里取消点赞行为方法
            [self.socialManager requestCancelPraiseOrCollectByUserId:kAccountUserID
                                                               objId:model.quizId
                                                             objType:@"2"
                                                                type:@"1"
                                                            Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                model.isParise = @(0);
                model.praiseTotal = @([model.praiseTotal intValue] - 1);
                [subscriber sendCompleted];
            }];
            
        }else{
            //这里执行点赞行为方法
            [self.socialManager requestPictorialPraiseAttentByObjId:model.quizId
                                                            ObjType:@"2"
                                                               Type:@"1"
                                                            Creator:[SEGProfileManager sharedManager].profile.nickname
                                                    objPicUrlForMsg:model.quizPic
                                                     objTitleForMsg:model.quizContent1
                                                     byReviewUserId:model.userId
                                                      communityName:communityName
                                                        parentObjId:model.quizId
                                                      parentObjType:SEGUserType_ACTIVITY
                                                      isTopicPraise:YES
                                                            topicID:self.objId
                                                           Finished:^(BOOL isSuccessed, NSString* codeType, NSString* errorMessage){
                model.isParise = @(1);
                model.praiseTotal = @([model.praiseTotal intValue] + 1);
                [subscriber sendCompleted];
            }];
        }
        
        return nil;
    }];
    return signal;
}

- (NSDictionary *)getShareParamsWithImage:(UIImage *)image {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:self.objId forKey:@"objID"];
    [params setValue:@(SEGShareVCType_Topic) forKey:@"shareVCType"];

    
    if (image) {
        [params setValue:image forKey:@"shareImage"];
    }else {
        if (self.topicManager.topicDetailModel.model.picture && self.topicManager.topicDetailModel.model.picture.count > 0) {
            NSString *imageUrl = [NSString stringWithFormat:@"%@%@",kClientSmallImageRootURL,self.topicManager.topicDetailModel.model.picture[0]];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]]];
            [params setValue:image forKey:@"shareImage"];
        }
    }
    
    NSString* shareUrlString = [NSString stringWithFormat:@"%@%@?#/topic/detail?objId=%@&objType=%@&app_platform_code=%@&company_platform_code=%@&scheme=%@", kClientRootURL, kNewShareURLPre, self.topicManager.topicDetailModel.model.id ,self.topicManager.topicDetailModel.model.objType, kAppPlatformCode, kAppPlatformCode, kOpenAppScheme];
    
    [params setValue:[NSString stringWithFormat:@"分享话题#%@#",self.topicManager.topicDetailModel.model.title] forKey:@"sharetitle"];
    [params setValue:self.topicManager.topicDetailModel.model.content forKey:@"sharecontent"];
    [params setValue:shareUrlString forKey:@"inviteurl"];
    return params;
}

- (RACSignal *)requestDeleteJoinHistory {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        [self.sharedNewManager requestDeleteJoinHistoryWithObjId:self.reportModel.quizId
         objType:self.reportModel.objType
        finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
            if (!isSuccessed) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)seg_requestPublishWithContent:(NSString *)content {
    @weakify(self);
    content = [content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    RACSignal *checkSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        if (content.length < 2) {
            [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"输入内容不能少于2个字。"}]];
            return nil;
        }else if (content.length > 70){
            [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"亲，您输入的内容已超过70字。"}]];
            return nil;
        }

        [subscriber sendCompleted];

        return nil;
    }];
    
    RACSignal *sendSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        //当昵称为空时传入手机号码
        SEGProfileModel* sysAccount = [SEGProfileManager sharedManager].profile /*SAM:登录FUNC*/;
        NSString* nickName = sysAccount.nickname;
        if ([nickName length] == 0) {
            nickName = sysAccount.tel;
        }
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:self.objId, @"objId",
                         @"5", @"objType",
                         @"内容", @"quizContent",
                         kAccountUserID, @"userId",
                         ValueToString(self.topicManager.topicDetailModel.model.quizTypeId), @"quizTypeId",
                         @"3", @"quizRangeId",
                         ValueToString(sysAccount.cityId), @"regionId", //城市编码
                         ValueToString(sysAccount.jobCommunity), @"organId", //小区id
                         ValueToString(self.topicManager.topicDetailModel.model.title), @"linkTitle",
                         @"", @"quizPic", //图片拼接
                         [NSString stringWithFormat:@"来自%@ %@", sysAccount.city, sysAccount.communityName], @"communityName", //城市+名称
                         //nickName, @"creator",
                         self.objId, @"linkUrl", nil];
        
        [params setValue:content forKey:@"quizContent"];
        [params setValue:[SEGProfileManager sharedManager].profile.jobCommunity forKey:@"communityId"];
        
        [subscriber sendNext:nil];
        SEGCommunitySocialManager *manager = [[SEGCommunitySocialManager alloc] init];
        [manager requestSaveQuizWithParams:params Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
            if (isSuccessed) {
                //话题发帖积分行为设置
                [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.topic module:SEGIntegralModule.topicDetail businessID:self.objId  finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                }];
                [subscriber sendCompleted];
            }else {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:codeType.integerValue userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }
        }];
        
        return nil;
    }];
    
    return [RACSignal concat:@[checkSignal,sendSignal]];
}

#pragma mark - private methods



#pragma mark - setter and getter
- (NSArray<SEGFindQuizListByQuizTypeModel *> *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

- (SEGNewTopicManager *)topicManager {
    if (!_topicManager) {
        _topicManager = [[SEGNewTopicManager alloc] init];
    }
    return _topicManager;
}

- (SEGCommunitySocialManager *)socialManager
{
    if (!_socialManager) {
        _socialManager = [[SEGCommunitySocialManager alloc] init];
    }
    return _socialManager;
}

- (SEGSharedNewManager *)sharedNewManager
{
    if (!_sharedNewManager) {
        _sharedNewManager = [[SEGSharedNewManager alloc] init];
    }
    return _sharedNewManager;
}

@end
